const { constant } = require("./constant");
const { coord } = require("./coordinate");

//###########################################
//##############    公用函数    ##############
//##########################################

export var utils = {
    /**
     * 加载APP
     * @param {*} appName 应用名称
     * @author guxiang
     */
    loadingApp(appName) {
        //打开应用
        app.launchApp(appName);
        sleep(4000);
        for (let i = 0; i < 5; i ++) {
            let open = this.containText('正在尝试开启');
            if (open) {
                let widget = className("android.widget.Button").text('允许').findOne(2000);
                if (widget != null) {
                    widget.click();
                    sleep(1000);
                }
            }
        }
        for (let i = 0; i < 5; i ++) {
            let permission = this.containText('访问以下权限');
            if (permission) {
                let widget = className("android.widget.Button").text('始终允许').findOne(2000);
                if (widget != null) {
                    widget.click();
                    sleep(1000);
                }
            }
        }

        return true;
    },

    /**
     * 退出APP进程
     * @param {*} times 后退次数
     */
    quitApp(times) {
        if (times < 1) times = 1;
        for (let i = 0; i < times; i ++) {
            back();
            sleep(800);
        }
    },

    /**
     * 通过坐标点击屏幕
     * @param {*} x x坐标
     * @param {*} y y坐标
     * @param {*} duration 等待时长
     * @author guxiang
     */
    coordinateClick(x, y, duration) {
        click(x, y);
        sleep(duration);
        return;
    },

    /**
     * 通过控件ID名点击坐标
     * @param {*} name id名
     * @param {*} duration 等待时长
     * @author guxiang
     */
    idNameClick(name, duration) {
        id(name).findOne().click();
        sleep(duration);
        return;
    },

    /**
     * 双击按钮
     * @author guxiang
     */
    doubleClick() {
        press(device.width / 2, device.height / 2, 100);
        sleep(100);
        press(device.width / 2, device.height / 2, 100);
    },

    /**
     * 获取设备信息
     * @author guxiang
     */
    deviceInfo() {
        let deviceId = device.getIMEI();
        if (deviceId == null) {
            deviceId = device.getAndroidId();
        }
        return '?phoneCode=' + deviceId + '&version=' + constant.APP_VERSION;
    },

    /**
     * 上报服务器
     * @author guxiang
     */
    notify(missionId, type) {
        let url = constant.REPORT_URL + this.deviceInfo() + "&taskLogId=" + missionId + "&type=" + type;
        http.get(url);
    },

    /**
     * 多次失败到达重试上限、通知服务器
     * @param {string} missionId 任务ID
     */
    failNotify(missionId) {
        console.info('fail 3 times...');
        let url = constant.FAIL_URL + this.deviceInfo() + "&taskLogId=" + missionId;
        let ret = http.get(url);
        console.info(ret);
    },

    /**
     * 随机获取数组的元素
     * @param {*} arr 容器数组
     * @author guxiang
     */
    randomArrItem(arr) {
        return arr[Math.floor(Math.random() * arr.length)];
    },

    /**
     * 判断场景加载是否成功
     * @param {*} activeName 场景名称
     * @author guxiang
     */
    checkActiveLoading(activeName, flag) {
        let act = currentActivity();
        if (act != activeName) {
            if (flag) {
                console.warn(activeName + ' wrong act...', act);
            }
            sleep(3000); //再等待3秒
            act = currentActivity();
            if (act != activeName) {
                if (flag) {
                    console.warn(activeName + ' wrong act...', act);
                } 
                sleep(3000);
                if (act != activeName) {
                    if (flag) {
                        console.warn(activeName + ' wrong act...', act);
                    } 
                    return false;
                }
            }
            if (flag) {
                console.info(activeName + ' mission continue...');
            } 
        }
        return true;
    },

    //多次执行函数
    doMuliFun(func, n, args) {
        for(let i = 0; i < n; i++) {
            func.call(this, args);
        }
    },

    /**
     * 通过ID找控件，3秒找不到返回null,找到就点击
     * @param {string} elm_id 控件ID
     */
    findOneByIdAndClick(elm_id){
        let el = id(elm_id).findOne(5000);
        if(el) {
            el.click();
            return true;
        }
        return false;
    },
    
    /**
     * 判断控件是否存在ByID
     * @param {string} elm_id 控件ID
     */
    checkExistsById(elm_id){
        let el = id(elm_id).findOne(2000);
        if(el){
            return true;
        }else{
            return false;
        }
    },

    /**
     * 判断控件是否存在
     * @param {*} widgetName 
     * @author guxiang 
     */
    checkWidget(widgetName) {
        let widget = className("android.widget.TextView").text(widgetName).findOnce();
        if (widget == null) {
            return false;
        } else {
            return true;
        }
    },

    /**
     * 
     * @param {*} context 
     */
    containText(context) {
        return textContains(context).findOne(2000) == null ? false : true;
    },

    /**
     * 获取适配应用的坐标
     * @param {*} appName 
     * @author guxiang
     */
    getFitCoordinate(appName) {
        let width = device.width;
        let height = device.height;
        if (appName == "抖音短视频") {
            if (width == 540 && height == 1200) {
                return coord.douyin.device_540_1200;
            } else if (width == 720 && height == 1520) {
                return coord.douyin.device_720_1520;
            } else if (width == 1080 && height == 1920) {
                return coord.douyin.device_1080_1920;
            } else if (width == 1080 && height == 2160) {
                return coord.douyin.device_1080_2160;
            } 
        }
        return null;
    },
    
    getPointByBL(w,h){
        let p = {};
        p.x = device.width * w;
        p.y = device.height * h;
        return p;
    },

    /**
     * 在控制台输出
     * @param {string} context 
     */
    outputMessage(context) {
        console.info(context);
    },

    /**
     * 杀死最近运行的所有进程
     */
    killAllProgress() {
        if (device.device == 'le_x620') {
            console.info('clear...');
            home();
            recents();
            sleep(2000);
            for (let i = 0; i < 5; i ++) {
                let button = this.swipeAndFind();
                if (button) {
                    let widget = id('button').findOne(2000);
                    sleep(2000);
                    widget.click();
                    break;
                }
            }
        } else {
            console.info('clear...');
            home();
            recents();
            let button = id('clearAnimView').findOne(2000);
            if (button != null) {
                button.click();
                sleep(1500);
            } else {
                back();
                sleep(1500);
            }
        }
    },

    /**
     * 心跳通知
     * @author guxiang
     */
    heartbeat() {
        console.info('heart');
        let url = constant.HEARTBEAT_URL + this.deviceInfo();
        //发起网络请求
        http.get(url);
    },

    /**
     * 划动屏幕寻找控件
     */
    swipeAndFind() {
        let start_x = device.width / 2;
        let start_y = device.height / 2;
        let end_x = device.width / 2;
        let end_y = device.height;

        gesture(300, [start_x, start_y], [end_x, end_y]);

        let button = id('button').findOne(2000);
        if (button != null) {
            return true;
        } else {
            return false;
        }
    }
}

